using CfgTable;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using System.Linq;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UILevelMain : UIEntityWindow
    {
        /// <summary>
        /// 静态配置
        /// </summary>
        private static UICreateConfig _createConfig = new()
        {
            prefabName = nameof(UILevelMain),
            layer = EUILayer.Main,
        };

        /// <summary>
        /// 创建UI的配置
        /// </summary>
        public override IUICreateConfig createConfig => _createConfig;

        #region Template Generate,don't modify

        protected partial class UIB_UILevelMain
        {
            #region ObjectBinding Generate

            public GameObject heroGrid { protected set; get; }
            public GameObject buff { protected set; get; }
            public ExButton btnSettlement { protected set; get; }
            public ExButton btnCollect { protected set; get; }
            public ExImage collectIcon { protected set; get; }
            public ExText collectNum { protected set; get; }
            public Animation mapNameAnim { protected set; get; }
            public ExText mapNameText { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<GameObject>("heroGrid", out var __tbv0);
                heroGrid = __tbv0;
                __binding.TryGetVariableValue<GameObject>("buff", out var __tbv1);
                buff = __tbv1;
                __binding.TryGetVariableValue<ExButton>("btnSettlement", out var __tbv2);
                btnSettlement = __tbv2;
                __binding.TryGetVariableValue<ExButton>("btnCollect", out var __tbv3);
                btnCollect = __tbv3;
                __binding.TryGetVariableValue<ExImage>("collectIcon", out var __tbv4);
                collectIcon = __tbv4;
                __binding.TryGetVariableValue<ExText>("collectNum", out var __tbv5);
                collectNum = __tbv5;
                __binding.TryGetVariableValue<Animation>("mapNameAnim", out var __tbv6);
                mapNameAnim = __tbv6;
                __binding.TryGetVariableValue<ExText>("mapNameText", out var __tbv7);
                mapNameText = __tbv7;
            }


            #endregion ObjectBinding Generate
        }

        #endregion Template Generate,don't modify

        /// <summary>
        /// 可以自定义修改的
        /// </summary>
        protected partial class UIB_UILevelMain
        {
            public virtual void StartBinding(GameObject __go)
            {
                var binding = __go.GetComponent<ObjectBinding>();
                if (binding != null)
                {
                    InitBinding(binding);
                }
            }
        }

        protected UIB_UILevelMain ui { get; set; }
        private UIMsgDispatcher currMsgDispatcher => _msgDispatcher as UIMsgDispatcher;

        private UIN_LevelHeroHeadList _heroHeadList;
        private UIN_LevelBuffOverView _buffOverView;
        private int _regionCollectionNum;
        private int _initialRegionCollectedNum;
        private int _collectionItemCid;
        private int _initialCollectedTotal;

        protected override void BeforeInit()
        {
            ui = new UIB_UILevelMain();
            ui.StartBinding(gameObject);
        }

        protected override void OnInit()
        {
            isUpdate = true;
            _heroHeadList = InitChildNode<UIN_LevelHeroHeadList>(ui.heroGrid);
            _buffOverView = InitChildNode<UIN_LevelBuffOverView>(ui.buff);
            _heroHeadList.Show();
            _heroHeadList.Refresh();
            _buffOverView.Show();
            //_buffOverView 的 buffItem 需要调用Update 因此需要把父节点的 isUpdate 打开
            ui.btnSettlement.onClick.AddListener(OnBtnSettlementClick);
            ui.btnSettlement.SetActive(false);
            InitRegionCollectItem();
        }

        protected override void OnShow(UIBaseData data)
        {

        }

        protected override void OnHide()
        {

        }

        public void PlayMapNameAnim(string mapName)
        {
            ui.mapNameAnim.gameObject.SetActive(true);
            ui.mapNameText.text = mapName;
            ui.mapNameAnim.Play();
        }

        private async UniTaskVoid InitCollectedNum(int regionCid)
        {
            _initialRegionCollectedNum = 0;
            var mapUIData = await MapUIModule.Instance.GetMapData(GameDataCenter.CurrGameArea, regionCid);
            foreach (var entity in mapUIData.entities)
            {
                var config = TableCenter.mapUiEntity.Get(entity.mapUIEntityCid);
                if (config.Type == MapUiEntityType.CollectItem)
                {
                    _initialRegionCollectedNum++;
                }
            }

            mapUIData.Put2Pool();
            ui.collectNum.text =
                APIUIFormation.GetRegionCollectionItemProgress(_regionCollectionNum - _initialRegionCollectedNum,
                    _regionCollectionNum);
        }

        protected override void AddMsgListeners()
        {
            currMsgDispatcher.AddListener(MsgEventType.Level_BattleSettlement, OnLevelBattleSettlement);
        }

        private void OnItemChanged()
        {
            //_collectionItemCid为0,表示该区域无可收集道具,直接返回
            //InitRegionCollectItem 已经关闭了btnCollect的显示
            if (_collectionItemCid == 0)
            {
                return;
            }

            var curTotal = ItemModule.Instance.GetNum(_collectionItemCid);
            var add = curTotal - _initialCollectedTotal;
            if (add > 0)
            {
                ui.collectNum.text = ui.collectNum.text =
                    APIUIFormation.GetRegionCollectionItemProgress(
                        _regionCollectionNum - _initialRegionCollectedNum + add,
                        _regionCollectionNum);
            }
        }

        private void OnLevelBattleSettlement()
        {
            ui.btnSettlement.SetActive(true);
        }

        private void OnBtnSettlementClick()
        {
            ui.btnSettlement.SetActive(false);
            var settlement = LevelPlayUtil.GetDynLevelPlayer()?.ObtainBattleSettlementData();
            if (settlement != null)
            {
                OpenUI<UIBattleSettlement>(UD_BattleSettlement.Create(settlement));
            }
        }

        private void OnBtnItemCollect()
        {
            OpenUI<UICollectItem>();
        }

        //切换区域时初始化当前区域收集道具数据
        private void InitRegionCollectItem()
        {
            ui.btnCollect.onClick.AddListener(OnBtnItemCollect);
            var regionCid = LevelPlayModule.Instance.levelPlay.regionCtrl.cfgRegionPack.cfgRegionInstance.Id;
            _regionCollectionNum = TableCenter.regionInstance.Get(regionCid)?.ExploreCollectionNum ?? 0;
            if (_regionCollectionNum == 0)
            {
                ui.btnCollect.SetActive(false);
                _collectionItemCid = 0;
            }
            else
            {
                ui.btnCollect.SetActive(true);
                _collectionItemCid = TableCenter.quest.Get(QuestModule.Instance.collectionQuestCid).TargetParams
                    .FirstOrDefault();
                _initialCollectedTotal = ItemModule.Instance.GetNum(_collectionItemCid);
                var itemConfig = TableCenter.item.Get(_collectionItemCid);
                if (itemConfig != null)
                {
                    SetImageSprite(ui.collectIcon, itemConfig.Icon_fullPath);
                }

                InitCollectedNum(regionCid).Forget();
                currMsgDispatcher.AddListener(MsgEventType.ItemChanged, OnItemChanged);
            }
        }

        protected override void OnDispose()
        {
        }
    }
}